<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .form{
            float: left;
        }
        table{
            float: left;
            margin-left: 50px;
            margin: 20px;
        }
        table tr th, table tr td{
            padding:5px;
        }
    </style>
</head>
<body>
    <div class="form">
        <p><label>Key  :<input type="text" id="key" placeholder="请输入键名"/></label></p>
        
        <p><label>Value:<input type="text" id="val" placeholder="请输入键值"/></label></p>

        <div>
            <button id="add">add</button>
            <button id="clear">clear</button>
        </div>

        <p>这里有 <span class="count">0</span> 个items</p>
    </div>

    <table class="table" border="1" rules="all">
        <thead>
            <tr>
                <th>Key</th>
                <th>Value</th>
            </tr>
        </thead>

        <tbody>
            <tr align="center">
                <td colspan="2">暂无数据</td>
            </tr>
        </tbody>
    </table>

    <script>
        var add = document.querySelector("#add");
        var key = document.querySelector("#key");
        var val = document.querySelector("#val");
        var tbody = document.querySelector("tbody");
        var countSpan = document.querySelector(".count");
        var clear = document.querySelector("#clear");
        function render(){
         

            var count = localStorage.length;
            countSpan.innerText = count;

            if( count == 0 ){
                tbody.innerHTML = `<tr align="center">
                    <td colspan="2">暂无数据</td>
                </tr>`;
                return;
            }

            var htmlStr = ``;
            for(var i = 0 ; i < count ; i++ ){
                var name =  localStorage.key(i);
                var zhi = localStorage.getItem( name );

                htmlStr += `
                    <tr align="center">
                        <td>${name}</td>
                        <td>${zhi}</td>
                    </tr>
                `;
            }
            tbody.innerHTML = htmlStr;
        }
        render();

        add.onclick = function(){
            var keyName = key.value;
            var keyValue = val.value;
            localStorage.setItem( keyName, keyValue );
            render();
            key.value = "";
            val.value = "";
            key.focus();
        }
        val.onkeydown = function( e ){
            if( e.keyCode == 13 ){
                add.onclick();
            } 
        }
        clear.onclick = function(){
            localStorage.clear();
            render();
        }
    </script>
</body>
</html>